import time

import numpy as np
from joblib import Memory

# 基于外存的缓存,把函数调用快照写入到磁盘里面，然后类似字典的方式进行查找


def costly_compute(data, column_index=0):
    """Simulate an expensive computation."""
    time.sleep(5)
    return data[column_index]


rng = np.random.RandomState(42)
data = rng.randn(int(1e5), 10)
start = time.time()
data_trans = costly_compute(data)
end = time.time()

print('\nThe function took {:.2f} s to compute.'.format(end - start))
print('\nThe transformed data are:\n {}'.format(data_trans))

print('-' * 12)

location = './cachedir'
memory = Memory(location, verbose=0)


def costly_compute_cached(data, column_index=0):
    """Simulate an expensive computation."""
    time.sleep(5)
    return data[column_index]


costly_compute_cached = memory.cache(costly_compute_cached)
start = time.time()
data_trans = costly_compute_cached(data)
end = time.time()

print('\nThe function took {:.2f} s to compute.'.format(end - start))
print('\nThe transformed data are:\n {}'.format(data_trans))

memory.clear()

# from joblib import Parallel, delayed
# parallel = Parallel(
#             n_jobs=self.n_job, verbose=0, pre_dispatch="2*n_jobs", backend="multiprocessing"
#         )
# tmp_result = parallel(
#     delayed(self.one_threshold_compute)(
#         labels=labels,
#         pred_scores=pred_scores,
#         threshold=threshold
#     )
#     for threshold in thresholds
# )
